/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.common.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.common.dto.Module;
import com.javaeye.common.dto.Role;
import com.javaeye.common.dto.User;

public class PermissionsHelper {
	
	protected static Log log = LogFactory.getLog(PermissionsHelper.class);
	
    public static List<Module> getUserMenuModuleList(User user, int parentId) {
    	 List<Module> userModules = new ArrayList<Module>();
    	 Set<Role> userRoles = user.getRoles();
    	 for (Role r : userRoles) {
    		 Set<Module> modules = r.getModules();
    		 for (Module m : modules) {
    			 if (m.getType() == 0 && m.getParentId() == parentId) {
    				 if (!userModules.contains(m)) {
        				 userModules.add(m);
        			 }
    			 }
    		 }
    	 }
    	 Collections.sort(userModules, new Comparator<Module>() {
			 public int compare(Module module1, Module module2) {
				 return module1.getOrderNum() - module2.getOrderNum();
			 }
		 });
    	 return userModules;
    }
    
	public static boolean checkHasPermissions(User user, Module module) {
		int moduleId = module.getId();
		Set<Role> userRoles = user.getRoles();
		for (Role r : userRoles) {
			Set<Module> modules = r.getModules();
			for (Module m : modules) {
				if (moduleId == m.getId()) {
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean checkHasPermissions(User user, String action) {
		Set<Role> userRoles = user.getRoles();
		for (Role r : userRoles) {
			Set<Module> modules = r.getModules();
			for (Module m : modules) {
				if (action.equals(m.getUrl())) {
					return true;
				}
			}
		}
		return false;
	}
}
